package cn.com.dashihui.api.interceptor;

import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.ResultField;
import cn.com.dashihui.api.common.ResultState;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.service.UserService;
import cn.com.dashihui.kit.DatetimeKit;

/**
 * 验证请求中是否携带有用户登录标识，如果有，则查询出对应的用户信息，供接下来controller使用，如果没有，则返回错误
 */
public class AuthLoginInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		BaseController c = (BaseController)inv.getController();
		String sessionid = c.getPara(ResultField.FIELD_USER_LOGIN_TOKEN);
		if(StrKit.isBlank(sessionid)){
			c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_EXCEPTED,"请先登录");
		}else if(sessionid.length()!=36){
			c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_ERROR,"请重新登录");
		}else{
			//根据SESSIONID查询出相应会话的登录用户基本信息
			User currUser = new UserService().findUserInfoBySessionid(sessionid);
			if(currUser==null){
				c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_EXCEPTED,"请先登录");
			}else{
				long time = DatetimeKit.StrToDate(currUser.get("time").toString()).getTime();
				long times = Long.parseLong(PropKit.get("constants.token.interval"));
				time = time + times;
				Date nowtime = new Date();
				if(currUser.getInt("sta")== 2){
					c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_EXCEPTED1,"已在别处登录，请重新登录");
				}else if(currUser.getInt("sta")== 3){
					c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_EXCEPTED2,"请先登录");
				}else if(time>nowtime.getTime()){
					//判断正确后，放入Controller的request中，以方便Controller中取出来用
					c.setAttr("sessionid", sessionid);
					c.setAttr(PropKit.get("constants.currentUserKey"), currUser);
					inv.invoke();
				}else{
					c.renderResult(ResultState.STATE_USER_LOGIN_TOKEN_EXCEPTED3,"登录过期，请先登录");
				}
			}
		}
	}
}
